package com.atguigu.springcloud.Controller;


import com.atguigu.springcloud.Service.PaymentService;
import com.atguigu.springcloud.entities.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class MyController {
    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverport;
    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/creat")
    public int create(Payment payment){
        int result=paymentService.create(payment);
        System.out.println("插入结果"+result);
        return result;
    }
    @GetMapping (value = "/payment/get/{id}")
    public String getPaymentById(@PathVariable("id") int id){
        Payment payment=paymentService.getPaymentById(id);
        return payment+"serverport:"+serverport;
    }
    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        List<String> services= discoveryClient.getServices();
        for(String element : services){
            System.out.println("*******element: "+element);
        }
        List<ServiceInstance>  instances =discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for(ServiceInstance instance : instances){
            System.out.println(instance.getInstanceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }
    @GetMapping(value = "/payment/lb")
    public String getPaymentLB(){
        return serverport;
    }
    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeout(){
        try
        {
            TimeUnit.SECONDS.sleep(3);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {

        }
        return serverport;
    }
}
